//
//  StopAnimationViewController.m
//  CoreAnimation
//
//  Created by 张国文 on 16/10/27.
//  Copyright © 2016年 hangzhouyijiyin. All rights reserved.
//

#import "StopAnimationViewController.h"

@interface StopAnimationViewController ()<CAAnimationDelegate>

@property (nonatomic, strong) UIView *backgroundView;

@property (nonatomic, strong) CALayer *imageLayer;

@end

@implementation StopAnimationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.backgroundView = [[UIView alloc] initWithFrame:self.view.frame];
    self.backgroundView.backgroundColor = [[UIColor grayColor] colorWithAlphaComponent:0.5];
    [self.view addSubview:_backgroundView];
    
    self.imageLayer = [CALayer layer];
    self.imageLayer.bounds = CGRectMake(0, 0, 160, 160);
    self.imageLayer.position = CGPointMake(self.view.center.x, 250);
    self.imageLayer.contents = (__bridge id _Nullable)([UIImage imageWithName:@"蒙版"].CGImage);
    [self.backgroundView.layer addSublayer:_imageLayer];
    
    UIButton *startButton = [UIButton buttonWithType:UIButtonTypeCustom];
    startButton.frame = CGRectMake(50, 400, 150, 30);
    [startButton setTitle:@"开始动画" forState:UIControlStateNormal];
    [startButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [startButton addTarget:self action:@selector(start:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:startButton];
    
    UIButton *stopButton = [UIButton buttonWithType:UIButtonTypeCustom];
    stopButton.frame = CGRectMake(50, 450, 150, 30);
    [stopButton setTitle:@"停止动画" forState:UIControlStateNormal];
    [stopButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [stopButton addTarget:self action:@selector(stop:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:stopButton];
}

// 开始动画
- (void)start:(UIButton *)button
{
    CABasicAnimation *animation = [CABasicAnimation animation];
    animation.keyPath = @"transform.rotation.z";
    animation.duration = 2.0;
    animation.toValue = @(2 * M_PI);
    animation.delegate = self;
    [self.imageLayer addAnimation:animation forKey:@"changeRotation"];
}

// 停止动画
- (void)stop:(UIButton *)button
{
    NSLog(@"动画：%@", [self.imageLayer animationForKey:@"changeRotation"]);
    [self.imageLayer removeAnimationForKey:@"changeRotation"];
}


// 一般说来，动画在结束之后被自动移除，除非设置removedOnCompletion为NO，如果你设置动画在结束之后不被自动移除，那么当它不需要的时候你要手动移除它；否则它会一直存在于内存中，直到图层被销毁。
- (void)animationDidStop:(CABasicAnimation *)anim finished:(BOOL)flag
{
    // flag为动画的停止方式，YES为自动停止，NO为手动停止
    NSLog(@"%@", flag? @"动画自动停止":@"动画手动停止");
}

@end
